new Vue({
    el: '#app',
    data: {
        categories: [],
        products: [],
        cartItems: [],
        selectedCategory: null,
        showCategories: false,
        currentCategoryName: '',
        defaultImage: '/images/products/default.png',
        showCart: false, // 添加缺失的属性
        loadingInstance: null // 添加loading实例
    },
    computed: {
        filteredProducts() {
            if (!this.selectedCategory) {
                return this.products;
            }
            return this.products.filter(product => product.categoryId === this.selectedCategory);
        },
        totalQuantity() {
            return this.cartItems.reduce((total, item) => total + item.quantity, 0);
        },
        cartItemNames() {
            return this.cartItems.map(item => `${item.name}×${item.quantity}`).join('，');
        }
    },
    async mounted() {
        try {
            console.log('Vue应用开始初始化...');

            await this.loadData();
            this.restoreCart();

            // 数据加载完成，通知隐藏Loading
            console.log('Vue应用初始化完成');
            if (window.hideAppLoading) {
                window.hideAppLoading();
            } else {
                // 备用方案
                setTimeout(() => {
                    const loading = document.getElementById('global-loading');
                    const app = document.getElementById('app');
                    if (loading) loading.style.display = 'none';
                    if (app) app.style.display = 'block';
                }, 1000);
            }

        } catch (error) {
            console.error('Vue应用初始化失败:', error);
            // 出错时也隐藏loading
            if (window.hideAppLoading) {
                window.hideAppLoading();
            }
        }
    },
    methods: {
        async loadData() {
            try {
                // 修复：使用正确的loading方法
                this.loadingInstance = this.$loading({
                    lock: true,
                    text: '加载中...',
                    background: 'rgba(0, 0, 0, 0.7)'
                });

                const [categoriesRes, productsRes] = await Promise.all([
                    API.category.getAll(),
                    API.product.getAll()
                ]);

                this.categories = categoriesRes.data || categoriesRes;
                this.products = productsRes.data || productsRes;

                // 确保图片URL有默认值
                this.products = this.products.map(product => ({
                    ...product,
                    imageUrl: product.imageUrl || this.defaultImage
                }));

                if (this.categories.length > 0 && !this.selectedCategory) {
                    this.selectCategory(this.categories[0]);
                }

                // 修复：正确关闭loading
                if (this.loadingInstance) {
                    this.loadingInstance.close();
                }

            } catch (error) {
                if (this.loadingInstance) {
                    this.loadingInstance.close();
                }
                this.handleApiError(error, '加载数据失败');
            }
        },

        selectCategory(category) {
            this.selectedCategory = category.id;
            this.currentCategoryName = category.name;
            this.showCategories = false;
            const productArea = document.querySelector('.product-area');
            if (productArea) {
                productArea.scrollTop = 0;
            }
        },

        toggleCategories() {
            this.showCategories = !this.showCategories;
        },

        addToCart(product) {
            const existingItem = this.cartItems.find(item => item.id === product.id);

            if (existingItem) {
                existingItem.quantity += 1;
            } else {
                this.cartItems.push({
                    id: product.id,
                    name: product.name,
                    quantity: 1,
                    price: product.price || 0
                });
            }

            this.saveCart();
            this.showMessage(`已添加 ${product.name}`, 'success');
        },

        saveCart() {
            localStorage.setItem('dishes_cart', JSON.stringify(this.cartItems));
        },

        restoreCart() {
            try {
                const savedCart = localStorage.getItem('dishes_cart');
                if (savedCart) {
                    this.cartItems = JSON.parse(savedCart);
                }
            } catch (error) {
                console.error('恢复购物车失败:', error);
                this.cartItems = [];
            }
        },

        goToCheckout() {
            if (this.cartItems.length === 0) {
                this.showMessage('请先选择餐品', 'error');
                return;
            }
            window.location.href = 'cart';
        },

        handleImageError(event) {
            console.log('图片加载失败:', event.target.src);
            event.target.style.display = 'none';
            // 查找或创建占位符
            const parent = event.target.parentElement;
            let placeholder = parent.querySelector('.product-image-placeholder');
            if (!placeholder) {
                placeholder = document.createElement('div');
                placeholder.className = 'product-image-placeholder';
                placeholder.innerHTML = '🍽️';
                parent.appendChild(placeholder);
            }
            placeholder.style.display = 'flex';
        },

        handleImageLoad(event) {
            event.target.style.opacity = '1';
            const placeholder = event.target.parentElement.querySelector('.product-image-placeholder');
            if (placeholder) {
                placeholder.style.display = 'none';
            }
        },

        // 添加消息提示方法
        showMessage(message, type = 'info') {
            this.$message({
                message: message,
                type: type,
                duration: 2000
            });
        },

        // 添加API错误处理方法
        handleApiError(error, defaultMessage = '操作失败') {
            console.error('API错误:', error);
            const message = error.message || defaultMessage;
            this.showMessage(message, 'error');
        },
        getImageUrl(imageName) {
            if (!imageName || imageName === 'null' || imageName === 'undefined') {
                return '/images/products/default.png';
            }
            // 直接拼接图片路径
            return `/images/products/${imageName}`;
        },

        // 修改handleImageError方法，添加更多调试信息
        handleImageError(event) {

            // 尝试加载默认图片
            if (event.target.src !== '/images/products/default.png') {
                event.target.src = '/images/products/default.png';
                return;
            }

            // 如果默认图片也加载失败，显示emoji
            event.target.style.display = 'none';
            const parent = event.target.parentElement;
            let placeholder = parent.querySelector('.product-image-placeholder');
            if (!placeholder) {
                placeholder = document.createElement('div');
                placeholder.className = 'product-image-placeholder';
                placeholder.innerHTML = '🍽️';
                parent.appendChild(placeholder);
            }
            placeholder.style.display = 'flex';
        }
    }
});